package top.goldenyear.porpoise.framework.isolate.core.util;

import java.util.function.Supplier;

/**
 * @author airhead
 */
public class TenantUtils {
  public static void execute(Long tenantId, Runnable runnable) {
    Long oldTenantId = TenantContext.getTenantId();
    try {
      TenantContext.enableTenant(tenantId);

      runnable.run();
    } finally {
      TenantContext.enableTenant(oldTenantId);
    }
  }

  public static <T> T execute(Long tenantId, Supplier<T> supplier) {
    Long oldTenantId = TenantContext.getTenantId();
    try {
      TenantContext.enableTenant(tenantId);

      return supplier.get();
    } finally {
      TenantContext.enableTenant(oldTenantId);
    }
  }

  public static void executeWithoutTenant(Runnable runnable) {
    Long tenantId = TenantContext.getTenantId();
    try {
      TenantContext.ignoreTenant();
      //      TenantManager.ignoreTenantCondition();

      runnable.run();
    } finally {
      //      TenantManager.restoreTenantCondition();
      TenantContext.enableTenant(tenantId);
    }
  }

  public static <T> T executeWithoutTenant(Supplier<T> supplier) {
    Long tenantId = TenantContext.getTenantId();
    try {
      TenantContext.ignoreTenant();
      //      TenantManager.ignoreTenantCondition();

      return supplier.get();
    } finally {
      //      TenantManager.restoreTenantCondition();
      TenantContext.enableTenant(tenantId);
    }
  }
}
